package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;

/**
 * 发表评论
 */
public class CommentActivity extends Activity {
    private static final String TAG = "CommentActivity";

    private TitleBar mTitleBar;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private EditText etComment;    //评论区域

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle = "取消";   //返回标题
    private static final String TITLE = "发表评论";
    private MyHandler mHandler;
    private String comment;
    private String did; //id
    private String ldid;    //文章id
    private int fromType;   //评论类型
    /**
     * 来源类型，用于区分评论种类
     */
    public interface FromType {
        /**
         * 文章中评论
         */
        int LONGDISTANCE_DETAIL = 1;
        /**
         * 动态评论
         */
        int DISCUSS_DETAIL = 2;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discuss_comment);
        init();
        findViews();
        setListeners();
    }

    /**
     * 初始化参数
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = CommentActivity.this;
        mContext = CommentActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        fromType = intent.getIntExtra(MyConstant.IntentKey.COMMENT_FROM, 0);
        switch (fromType) {
            case FromType.DISCUSS_DETAIL:
                did = intent.getStringExtra(MyConstant.IntentKey.DID);
                break;
            case FromType.LONGDISTANCE_DETAIL:
                ldid = intent.getStringExtra(MyConstant.IntentKey.LDID);
                break;
            default:
                break;
        }

        mHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        etComment = (EditText) this.findViewById(R.id.et_comment);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //对发送的监听
        mTitleBar.setRightOperation("发送", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                comment = etComment.getText().toString().trim();
                submitComment();    //发送评论
            }
        });
    }

    /**
     * 评论
     */
    private void submitComment() {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if (!Validator.isEffective(comment)) {
            T.shortToast(mContext, "评论不能为空！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();

        switch (fromType) {
            case FromType.DISCUSS_DETAIL:
                param.put(MyConstant.RequireParams.DID, did);
                param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.DISCUSS_COMMENT);
                param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.DISCUSS_COMMENT);
                break;
            case FromType.LONGDISTANCE_DETAIL:
                param.put(MyConstant.RequireParams.LDID, ldid);
                param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.LONGDISTANCE_COMMENT);
                param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.LONGDISTANCE_COMMENT);
                break;
            default:
                break;
        }
        param.put(MyConstant.RequireParams.COMMENT, comment);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final CommentActivity activity = (CommentActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.setMessage("正在提交...");
                                mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == MyConstant.DataType.DISCUSS_COMMENT) {
                                SparseArray<Object> commentResult = (SparseArray<Object>) msg.obj;
                                if (commentResult != null) {
                                    String errno = (String) commentResult.get(0);
                                    if (Validator.isEffective(errno)) {
                                        if(errno.equals("0")) { //成功
                                            Intent intent = new Intent();
                                            activity.setResult(MyConstant.IntentForResultCODE.DISCUSS_COMMENT_RESULTCODE, intent);
                                            activity.finish();
                                        }
                                    }
                                }
                            } else if (msg.arg1 == MyConstant.DataType.LONGDISTANCE_COMMENT) {
                                SparseArray<Object> commentResult = (SparseArray<Object>) msg.obj;
                                if (commentResult != null) {
                                    String errno = (String) commentResult.get(0);
                                    if (Validator.isEffective(errno)) {
                                        if(errno.equals("0")) { //成功
                                            Intent intent = new Intent();
                                            activity.setResult(MyConstant.IntentForResultCODE.LONGDISTANCE_COMMENT_RESULTCODE, intent);
                                            activity.finish();
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
